package org.gitee.weapp.controller;

import com.github.pagehelper.PageHelper;
import org.apache.http.HttpStatus;
import org.apache.ibatis.annotations.Param;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.common.constant.Constant;
import org.gitee.weapp.domain.entity.Order;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.domain.vo.OrderVo;
import org.gitee.weapp.mapper.OrderMapper;
import org.gitee.weapp.service.OrderService;
import org.gitee.weapp.service.TokenService;
import org.gitee.weapp.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HttpServletRequest request;

    @Value("${server.remote-address}")
    private String host;

    @Value("${server.port}")
    private Integer port;

    @PostMapping("/add")
    public AjaxResult addOrder(@RequestBody Order order) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error(HttpStatus.SC_NOT_FOUND, "用户未登录");
        }
        orderService.addOrder(order, sysUser);
        return AjaxResult.success("插入成功");
    }

    @GetMapping("/list")
    public AjaxResult getOrderList(@Param("type") Integer type, Integer pageNum, Integer pageSize) {
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        if (pageNum < 0 || pageSize < 0) {
            return AjaxResult.error(HttpStatus.SC_BAD_REQUEST, "分页不能小于0");
        }

        PageHelper.startPage(pageNum, pageSize);
        List<OrderVo> list = orderMapper.getOrderListById(type);
        list.forEach(orderVo -> {
            orderVo.getGoodsDetailList().forEach(goods -> {
                goods.setPicUrl("http://" + host + ':' + port + "/goods/pic?goodsId=" + goods.getId());
            });
        });
        return AjaxResult.success(list);
    }

    @GetMapping("/get")
    public AjaxResult getOrderById(@RequestParam("id") String orderId) {
        OrderVo orderVo = orderMapper.getOrderById(orderId);
        if (null == orderVo) {
            return AjaxResult.error(HttpStatus.SC_NOT_FOUND, "未查询到订单");
        }
        orderVo.getGoodsDetailList().forEach(goods -> {
            goods.setPicUrl("http://" + host + ':' + port + "/goods/pic?goodsId=" + goods.getId());
        });
        return AjaxResult.success(orderVo);
    }
}
